package com.qihoo.finance.backup;

import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mongodb.MongoClient;
import com.qihoo.finance.backup.reader.JdbcStreamBackReader;
import com.qihoo.finance.backup.writer.MongoBackWriter;

import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Application {

    private static final String jdbcUrl = "jdbc:mysql://db.360haojie.loan:3306/pcs?useUnicode=true";
    private static final String jdbcUser = "pcs_dev";
    private static final String jdbcPassword = "pcs_dev123";

    public static void main(String[] args) throws SQLException, JsonProcessingException, InterruptedException {
        final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        JdbcStreamBackReader streamBackReader = new JdbcStreamBackReader();
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUser);
        dataSource.setPassword(jdbcPassword);
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(1);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setPoolPreparedStatements(false);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(30);
        dataSource.setValidationQuery("select 1");
        // init
        streamBackReader.setDataSource(dataSource);
        streamBackReader.setRows(10);
        streamBackReader.setSql("select * from pc_weixin_recon_diff;");

        MongoClient mongoClient = new MongoClient("10.94.90.46", 27017);
        MongoBackWriter backWriter = new MongoBackWriter();
        backWriter.setMongoClient(mongoClient);
        backWriter.setDatabase("sql_test_db");
        backWriter.setCollection("sql_test_collection");

        StreamBacker streamBacker = new StreamBacker(streamBackReader, backWriter);
        singleThreadExecutor.execute(() -> {
            try {
                Result result = streamBacker.invoke();
                System.out.println("invoke finished");
                System.out.println("hasError: " + result.hasError());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        TimeUnit.MINUTES.sleep(60);
        streamBacker.stop();
    }
}
